/* eslint-disable */
import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Select,
  Icon,
  Input,
  Button,
  Tag,
  Modal,
  Divider,
  message,
  Drawer,
} from 'antd';
import { connect } from 'dva';
import SlickTable from '@/components/SlickTable';
// import useSlickTable from '@/hooks/useSlickTable';
import { useAntdTable } from '@umijs/hooks';
import { getPageSizeByCardHeight } from '@/utils/utils';
import request from '@/utils/request';
import Edit from './components/Edit';
const namespace = 'assemblyConfig';
const judgeObj = obj => {
  if (Object.keys(obj).length == 0) return true;
  else return false;
};

function AssemblyConfig({ size: { height }, form, dispatch }) {
  const [selectedRows, setSelectedRows] = useState([]);
  const [size, setSize] = useState(getPageSizeByCardHeight(height - 64 - 8));
  const { getFieldDecorator } = form;

  const [paramsObj, setParamsObj] = useState({});
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState('edit');
  const [assTypeMap, setAssType] = useState([]);

  // 通过dva存当前需要传递的数据
  const savePassData = params => {
    dispatch({
      type: `${namespace}/savePassData`,
      payload: params,
    });
  };

  useEffect(() => {
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'RmAssembly',
        attrNbr: 'assType',
      },
    })
      .then(res => {
        setAssType(res);
      })
      .always(() => setLoading(false));
  }, []);

  const getTableData = ({ current, pageSize, paramsObj }) => {
    return request('pmc/pms/RuleCfgController/findAssemblyPageQry', {
      data: {
        page: current,
        rowNum: pageSize,
        pageNum: current,
        pageSize: pageSize,
        // sortName: '',
        // sortOrder: 'asc',
        // filterCol: 'paramCode,paramName,paramValue,groupCode,groupName',
        ...paramsObj,
      },
    }).then(res => {
      if (Array.isArray(res.data.records)) {
        return {
          total: res.data.total,
          data: res.data.records.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTableData({ ...params, pageSize: size, paramsObj });
    },
    [paramsObj, height],
    {
      defaultPageSize: size,
      form,
    }
  );
  const { pagination, ...restTableProps } = tableProps;

  useEffect(() => {
    setSize(getPageSizeByCardHeight(height - 64 - 8));
  }, [height]);

  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      let obj = {};
      for (let item in fieldsValue) {
        if (fieldsValue[item] != undefined && fieldsValue[item] != '') {
          obj[item] = `${fieldsValue[item]}`;
        }
      }
      setParamsObj(obj);
    });
  };

  const handleSelectRows = value => {
    setSelectedRows(value);
  };

  const handleEdit = record => {
    setVisible(true);
    savePassData(record);
    if (judgeObj(record)) {
      setStatus('add');
    } else {
      setStatus('edit');
    }
  };

  const onClose = () => {
    setVisible(false);
  };

  const handleEffect = record => {
    Modal.confirm({
      content: '确定要删除吗?',
      onOk() {
        request('pmc/pms/RuleCfgController/deleteAssembly', {
          data: { assId: record.assId },
          method: 'POST',
        }).then(res => {
          if (res) {
            refresh();
          } else {
            message.error('操作失败！');
          }
        });
      },
    });
  };

  const handleReash = () => {
    // console.log("刷新")
    Modal.confirm({
      content: '确定要刷新缓存吗?',
      onOk() {
        request('pmc/pms/BmDataDictController/reload', { method: 'GET' }).then(res => {
          res === true ? message.success('缓存刷新成功！') : message.error('缓存刷新失败！');
        });
      },
    });
  };

  const handleCopy = () => {
    let arr = [];
    selectedRows.map(item => {
      arr.push(item.dataDictId);
    });
    request('pmc/pms/BmDataDictController/copy', { data: arr }).then(res => {
      if (res && res.length > 0) {
        refresh();
        setSelectedRows([]);
        message.success('复制成功！');
      } else {
        message.error('复制失败！');
      }
    });
  };

  const handleReset = () => {
    form.resetFields();
  };

  const columns = [
    {
      title: '业务组件名称',
      dataIndex: 'assName',
      ellipsis: true,
    },
    {
      title: '业务组件编码',
      dataIndex: 'assCode',
      ellipsis: true,
    },
    {
      title: '组件类型',
      dataIndex: 'assTypeName',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createDateStr',
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                handleEdit(record);
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleEffect(record);
              }}
            >
              删除
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <>
      <Card
        title="业务组件列表"
        style={{ minHeight: height }}
        className="cute"
        extra={
          <div style={{ display: 'inline-block' }}>
            <Button
              className="margin-right"
              type="primary"
              onClick={() => {
                handleEdit({});
              }}
            >
              新增
            </Button>
          </div>
        }
      >
        <Form className="flow fix-label">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="业务组件名称">
                {getFieldDecorator('assName')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="业务组件编码">
                {getFieldDecorator('assCode')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="组件类型">
                {getFieldDecorator('assType')(
                  <Select allowClear placeholder="请选择">
                    {assTypeMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6} className="text-right">
              <Button type="primary" onClick={submit}>
                查询
              </Button>
              <Button className="margin-left" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <SlickTable
          style={{ marginTop: 8 }}
          rowKey={record => record.assId}
          columns={columns}
          {...restTableProps}
          data={{
            pagination: {
              ...pagination,
              pageSize: size,
            },
          }}
        />
      </Card>
      <Drawer
        title={status === 'edit' ? '编辑业务组件' : '新增业务组件'}
        destroyOnClose
        width={620}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Edit close={onClose} refresh={refresh} />
      </Drawer>
    </>
  );
}
export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(AssemblyConfig));
